package com.shopping.controller;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/api/images")
public class ImageController {

    @GetMapping("/{imageName}")
    public ResponseEntity<byte[]> getImage(@PathVariable String imageName) throws IOException {
        // 首先尝试从上传目录获取图片
        Path uploadPath = Paths.get("uploads/images", imageName);
        if (Files.exists(uploadPath)) {
            byte[] imageBytes = Files.readAllBytes(uploadPath);
            return ResponseEntity.ok()
                    .contentType(MediaType.IMAGE_JPEG)
                    .body(imageBytes);
        }

        // 如果上传目录没有，则尝试从静态资源目录获取默认图片
        Resource resource = new ClassPathResource("static/images/" + imageName);
        if (resource.exists()) {
            try (InputStream inputStream = resource.getInputStream();
                 ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                return ResponseEntity.ok()
                        .contentType(MediaType.IMAGE_JPEG)
                        .body(outputStream.toByteArray());
            }
        }

        // 如果都找不到，返回404
        return ResponseEntity.notFound().build();
    }
}